package com.youdianda.controller;


import com.youdianda.constant.MessageConstant;
import com.youdianda.result.Result;
import com.youdianda.util.AliOssUtil;
import com.youdianda.vo.UploadVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
@Api(tags = "通用接口")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    public Result upload(MultipartFile file, String type) {
        try {
            String originalFilename = file.getOriginalFilename();
            long size = file.getSize();
            log.info("上传文件：文件原始名：{}, 文件大小：{}, 文件类型：{}", originalFilename, size, type);
            String fileName = UUID.randomUUID().toString().replace("-", "") + originalFilename.substring(originalFilename.lastIndexOf("."));
            String url = aliOssUtil.upload(file.getBytes(), fileName);
            UploadVO uploadVO = UploadVO.builder()
                    .savePath(url)
                    .name(fileName)
                    .mime(type)
                    .size((int) size)
                    .build();
            return Result.success(uploadVO);
        } catch (Exception e) {
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }

    }

}
